package com.fa4j.common.web.interceptor;

import com.fa4j.common.web.annotation.ApiMethod;
import com.fa4j.common.web.config.CommonWebPropsConfig;
import com.fa4j.common.web.model.CommonWebConst;
import com.fa4j.common.web.model.ServiceMode;
import com.fa4j.common.web.util.ClientUtil;
import com.fa4j.common.web.util.ContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@RequiredArgsConstructor
public class CommonWebHandlerInterceptor implements HandlerInterceptor {

    private final CommonWebPropsConfig config;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        ContextUtil.set(ClientUtil.getClientInfo(request));
        if (handler instanceof HandlerMethod hm) {
            ApiMethod apiMethod = hm.getMethodAnnotation(ApiMethod.class);
            if (apiMethod == null && config.getMode() == ServiceMode.STANDALONE) {
                log.warn("单体模式下不能访问内部接口:{}", request.getRequestURI());
                return false;
            }
            if (apiMethod == null && config.getMode() == ServiceMode.MICROSERVICE) {
                //微服务模式下，需要header存在标记才能访问 x-service-from
                String serviceFrom = request.getHeader(CommonWebConst.HEADER_SERVICE_FROM);
                if (ObjectUtils.isEmpty(serviceFrom)) {
                    log.warn("微服务模式下内部接口无服务来源标记不能访问，path={}", request.getRequestURI());
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ContextUtil.removeAll();
    }
}
